% File estima_out
% followed after estima_loop
% analyzing reults from estima
% record settings and write them to an excel file. 
% cucd = 'O:\PROJ_LIB\LJM\exog'; 
% cd(cucd); 
% %
% cd('O:\PROJ_LIB\LJM\exog\udsregnosmebnd\lindtr\1trend z tight u addL2Y corr2\05 10 10 run1'); 
% 
% % load tab_loop;
% % load mat_loop; 
% load workspace; 
% % cucd=pwd; 
cucd = pwd; 

if ~isempty( findstr(outpath,'home') ); 
    %temp=findstr(upper(outpath),'LMJ'); 
    temp=findstr(upper(outpath),'LJM'); 
    outpath=['O:\PROJ_LIB\LJM',outpath(temp+3:end)]; 
    cd(outpath);     
end

if ~isempty( findstr(loadpath,'home') ); 
    %temp=findstr(upper(loadpath),'LMJ'); 
    temp=findstr(upper(loadpath),'LJM'); 
    loadpath=['O:\PROJ_LIB\LJM',loadpath(temp+3:end)]; 
    cd(loadpath);     
end


cd(cucd); 

logpostdvec = logpostd_mat(:, 2); 
[junk, order_descend] = sort(logpostdvec, 'descend'); 
% PARMODE_MAT=parmodemat(:,order_descend) 
% OPTIMAT 
% LOGLIKEL_MAT
parmodemat_descend = parmodemat(:, order_descend); 
optimat_descend = optimat(:, order_descend); 

cd(loadpath);
eval(set_fname); 
cd(cucd); 


%%
if exist('add2func','var')==1 && ~isempty(add2func) 
    dispaj('Switching function handle from ',func2str(funcmod)); 
    dispaj('to  ',[func2str(funcmod),add2func]);
    disp(' ');
    disp('Verifying solutions match...');
    pause(0.25);
    [var1,var2,difvar,difc]=checkmodels_lmj(funcmod,...
        str2func([func2str(funcmod),add2func]),parmodemat_descend(:,1),solveopt,addsol);
    if difvar < 1e-7;
        disp('Solutions identical')
    else
        disp('Solutions do not match')
    end
    
    if difc < 1e-10;
        disp('Constants identical');
    else
        disp('Constants do not match');
    end
    clear var1 var2 difvar difc
    funcmod=str2func([func2str(funcmod),add2func]);
    
    disp('Changed funcmod handle')        
end 


%% write in estimated parameters
nstrvals=size(parmodemat,2);
% create tabs for sorted results
estpar_tab_d=emptycell(numpar+7,nstrvals+1);
estpar_tab_d(1:numpar,1)=parnames;
estpar_tab_d(numpar+2:end,1)={'logPost';'logLikel';'Number';'Iteration count';'exitflag';'minutes'};

estpar_tab_d(1:numpar,2:end)=num2cprec(parmodemat_descend, 15);
estpar_tab_d(numpar+2,2:end)=num2cprec(logpostd_mat(order_descend, 2)');
estpar_tab_d(numpar+3,2:end)=num2cprec(loglikel_mat(order_descend,2)');
estpar_tab_d(numpar+4,2:end)=num2cprec(order_descend');
estpar_tab_d(numpar+5:numpar+7, 2:end)= num2cprec(optimat_descend); 



%% write in info about data 
datainfo_tab = emptycell(7, nstrvals + 1); 
datainfo_tab(1, 1:2) = {'data file', data_fname};
datainfo_tab(2, 1:2) = {'data path', data_path}; 
datainfo_tab(3, 1:2) = {'data range', [num2str(dataopt.start), ' to ', num2str(dataopt.finish)]}; 
datainfo_tab(4, 1:2) = {'data estimated', [num2str(dataopt.starest), ' to ', num2str(dataopt.finishest)]};
datainfo_tab(5, 1:2) = {'demean', num2str(dataopt.demean)};
datainfo_tab(6, 1:2) = {'demean type', num2str(dataopt.demean_type)};

datasum_tab = emptycell(nstrvals+1, size(Y, 2) + 1); 
datasum_tab{1, 1} = 'Series Names'; 
datasum_tab(1, 2:end) = Ynames; 
datasum_tab{2, 1} = 'mean';
datasum_tab(2, 2:end) = num2cprec(nanmean(Y));
datasum_tab{3, 1} = 'std dev';
datasum_tab(3, 2:end) = num2cprec(nanstd(Y));
datasum_tab = datasum_tab'; 

%% write in info about solution 

funcinfo_tab = emptycell(4, 2); 
funcinfo_tab(1, 1:2) = {'model', func2str(funcmod)}; 
funcinfo_tab(2, 1:2) = {'TolFun', num2str(solveopt.TolFun)};
funcinfo_tab(3, 1:2) = {'MaxIter', num2str(solveopt.MaxIter)};
funcinfo_tab(4, 1:2) = {'MaxFunEvals', num2str(solveopt.MaxFunEvals)}; 

%% write in info about estimation 
estinfo_tab = emptycell(5, 2); 
switch case_estima
    case 1
        eststr = 'CSMINWEL';
    case 2
        eststr = 'FMINCON'; 
    case 3
        eststr = 'Giorgio SA'; 
    case 4
        eststr = 'Simulated Annealing'; 
    case 5
        eststr = 'FMINSEARCH'; 
end 
estinfo_tab(1, 1:2) = {'outpath', outpath}; 
estinfo_tab(2, 1:2) = {'routine', eststr}; 
estinfo_tab(3, 1:2) = {'TolFun', num2str(estimopt.TolFun)}; 
estinfo_tab(4, 1:2) = {'MaxIter', num2str(estimopt.MaxIter)}; 
estinfo_tab(5, 1:2) = {'MaxFunEvals', num2str(estimopt.MaxFunEvals)}; 

%% write cells to Excels
% mod_est_info_tab = emptycell(7, 2); 
% mod_est_info_tab(1:5, 1:2) = estinfo_tab(1:5, :); 
%mod_est_info_tab(6:10, 1:2) = funcinfo_tab(1:5, :); 

mod_est_info_tab = merge_cells(estinfo_tab, funcinfo_tab, 2); 

% emptyline = emptycell(2, nstrvals + 1); 
% outcell = [mod_est_info_tab; datainfo_tab;  datasum_tab; emptyline; estpar_tab_d; emptyline; ss_tab_d];
outcell = merge_cells(mod_est_info_tab, datainfo_tab, 2); 
outcell = merge_cells(outcell, datasum_tab, 2); 
outcell = merge_cells(outcell, estpar_tab_d, 2); 
%outcell = merge_cells(outcell, ss_tab_d, 2);


%% Posterior Analysis

% npoints = 15; 
% modname = 'lmj_postmax'; 
% parmode = parmodemat_descend(:, 1); 
% x = parmodemat_descend(parposest, 1); 
% step = 2/npoints; 
% 
% 
% try
%     addsol.flag_mixfreq = flag_mixfreq; 
%     addsol.flag_gtv = flag_gtv; 
% catch
% end
% 
% posterioropt.outfold = outpath; 
% 
% if ~exist('Hes', 'var'); % if we have computed the Hessian before. 
%     Hes = [];
% end
% 
% [temp_mat,Hes,stdcell]=posterior_eval_lmjexog(x,step,npoints,modname, ...
%     parmode, Hes,parposest,funcmod,Y,trainvec, prpar, prss, solveopt, addsol, ssposest, parnames, posterioropt);
% close all;
% cd(outpath); 
% save workspace; 
% cd(cucd); 
%% 
% outcell = merge_cells(outcell, emptyline); 
% outcell = merge_cells(outcell, stdcell, 2); 
% cd(outpath);
% if isunix==0
%     xlswrite(load_fname, outcell, 'Est Result');
% else
%     savecell(outcell,[],outpath,'Est Result');
% end
% cd(cucd); 

%% write values of top mode to excel. 
topmode_tab = [parnames,  num2cprec(parmodemat_descend(:, 1), 15)]; 
cd(outpath)
xlswrite('top mode', topmode_tab); 
cd(cucd)

save_path = [outpath, '\top mode']; 
mkdir(save_path); 
temp      = extrsubf(loadpath, cucd ); 

if flag_rununix == 0; 
    tempos    = findstr(temp,'\'); 
elseif flag_rununix == 1; 
    tempos    = findstr(temp,'/'); 
end
root=temp(tempos(1):tempos(2)-1); 
spec=temp(tempos(2):tempos(3)-1); 
subf=temp(tempos(3):end        ); 
outfolder = extrsubf(save_path, loadpath);
topcell = {'root', root;
    'spec', spec;
    'subf', subf;
    'outfolder', outfolder
    'data', data_fname};

%% write smoothed states to excel file

[GG, RR, CONS, eu, SDX, ZZ, outfield, ssvec, flag, ssnames, stanames, shonames] = feval(funcmod,   parmodemat_descend(:, 1)); 

%[stt,etamat,smooth_st,yfor,vstar,logL,countmat,countobs,countszero,likelvec]=lmj_kfiltercentral(parmodemat_descend(:, 1),funcmod,Y,trainvec,[],[]); 
addsol.flag_mixfreq=flag_mixfreq;
addsol.flag_gtv     =flag_gtv;
[stt,etamat,smooth_st,yfor,vstar,logL,countmat,countobs,countszero]=lmj_kfiltercentral(parmodemat_descend(:, 1),funcmod,Y,trainvec,solveopt,addsol);
resfile = 'smoothed_states';


%% Add constant to Z states 
if flag_mixfreq==1
    ZZ=[ZZ;outfield.AA]; 
end 
znames=cell(size(ZZ,1),1);
pos_obsinstates=zeros(length(znames),1); 
for ii=1:length(znames)
    temp      =find(ZZ(ii,:)~=0 ) ;
    if length(temp) > 1
        error('Need 1 entry only for each row of ZZ')
    end
    znames(ii)=stanames( temp );
    pos_obsinstates(ii)=temp; 
end
if length(znames)~=size(Y,2); 
    error('Mistmatch ZNAMES and Cols in Y') 
end 

disp('Added constant back to observables'); 
COBS=repmat( (ZZ*CONS)',[size(Y,1) 1]);
smooth_st(:,pos_obsinstates)=smooth_st(:,pos_obsinstates)+COBS;


cd(outpath)
xlswrite(resfile,crtcell(smooth_st(:,1:length(stanames)),num2cprec(sample),stanames),'Twosided');
cd(cucd);


posLF=(outfield.NUMIT:outfield.NUMIT:length(sample))'; 

[YLF,outcell]=convertHtoL_av(smooth_st(:,pos_obsinstates),sample,outfield.NUMIT,pos_obsinstates,znames); 
cd(outpath); 
xlswrite(resfile,crtcell(YLF,num2cprec(sample),znames),'LFinHF');
xlswrite(resfile,crtcell(YLF(posLF,:),num2cprec(sample(posLF)),znames),'LFinLF');
cd(cucd); 
%%
cd(outpath); 
save smooth_state stt etamat smooth_st yfor vstar logL countmat countobs countszero likelvec stanames
cd(cucd); 
%% Write

